package com.example.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.pojo.Result;
import com.example.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

//    执行流程：浏览器 -> Filter -> DispatcherServlet -> Interceptor -> Controller      所以执行在Filter之后

    @Override//目标方法执行前运行，返回true：放行  返回false 不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /**
         * 该方法用于登录校验
         * 获取到请求头的token的jwt，然后进行解析，出为空或者出异常则没登录
         */
        return loginVerify(request, response);
    }

    private static boolean loginVerify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jwt = request.getHeader("token");
        if (!StringUtils.hasLength(jwt)){
            log.info("JWT令牌为空！");
            Result notLogin = Result.error("NOT_LOGIN");
            String notLoginStr = JSONObject.toJSONString(notLogin);
            response.getWriter().write(notLoginStr);
            return false;
        }
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("JWT令牌错误！");
            Result notLogin = Result.error("NOT_LOGIN");
            String notLoginStr = JSONObject.toJSONString(notLogin);
            response.getWriter().write(notLoginStr);
            return false;
        }
        log.info("JWT令牌正确！");
        log.info("拦截器的preHandle方法执行了，调用方法前执行");
        return true;
    }


}
